简体   繁体   English

使用鼠标事件进行绘制时,矩形未显示在画布中

[英]Rectangle not displaying in canvas when drawing with mouse events

I'm trying to draw a rectangle with mouse events, it seems to work, I've used console.log in all my code to see what is happening, and is all running nice, but the rectangle just dislikes me I think, it doesn't appear! 我正在尝试用鼠标事件绘制一个矩形,它似乎可以正常工作,我在所有代码中都使用console.log查看正在发生的情况,并且运行良好,但是矩形不喜欢我,我认为,没有出现!

I can't figure out how to find the mistake! 我不知道如何找到错误!

I only want a direction, thank you for your time. 我只想要一个方向,谢谢您的时间。

Fiddle here. 在这里摆弄。

And the code here: 和这里的代码:

$("body").wrapInner("<canvas id='myCanvas'>");
var canvas = $("#myCanvas").css("cursor", "crosshair");
var context = canvas[0].getContext("2d");
var div = {x:0, y:0};
var draw_rectangle = function(e){
    context.fillRect (
        div.x, div.y,
        (e.pageX - div.x),
        (e.pageY - div.y)
    );
};
context.fillStyle = "#aaf";
canvas.on("mousedown", function(e){
    div.x = e.pageX;
    div.y = e.pageY;
    canvas.on("mousemove", draw_rectangle);
});
canvas.on("mouseup", function(){
    canvas.off("mousemove");
    console.log("Drawed.");
});

The thing is, that the css properties``height and width are problematic with canvas elements, because they stretch your canvas element to fit the given size - stretching the canvas' bitmap. 事实是, css properties``height canvas' canvas元素的高度和width存在问题,因为它们会拉伸画布元素以适合给定的大小-拉伸canvas'位图。 The html properties height and width on the other hand determine the size of your canvas' bitmap. html properties heightwidth决定了canvas'位图的大小。

So, a solution in your case would be, to change your code to the following: 因此,针对您的情况的解决方案是将代码更改为以下内容:

 $("body").wrapInner("<canvas id='myCanvas'>"); $('#myCanvas').attr("width", 400); $('#myCanvas').attr("height", 500); var canvas = $("#myCanvas").css("cursor", "crosshair"); var context = canvas[0].getContext("2d"); var div = {x:0, y:0}; var draw_rectangle = function(e){ context.fillRect ( div.x, div.y, (e.pageX - div.x), (e.pageY - div.y) ); }; context.fillStyle = "#aaf"; canvas.on("mousedown", function(e){ div.x = e.pageX; div.y = e.pageY; canvas.on("mousemove", draw_rectangle); }); canvas.on("mouseup", function(){ canvas.off("mousemove"); console.log("Drawed."); }); 
 canvas { background-color: rgba(0, 0, 0, 0.3); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Information Source: Canvas is stretched when using CSS but normal with "width" / "height" properties 信息来源: 使用CSS时画布是拉伸的,但是具有“宽度” /“高度”属性的法线

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM