我正在尝试使用鼠标事件绘制一个矩形,它似乎工作,我在我的所有代码中使用 console.log 来查看发生了什么,并且运行良好,但矩形只是不喜欢我,我想,它不会出现!
我无法弄清楚如何找到错误!
我只想要一个方向,谢谢你的时间。
这里的代码:
$("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.");
});
答案 0 :(得分:1)
问题是,css properties``height
和width
对canvas
元素有问题,因为它们会拉伸您的canvas元素以适合给定的大小 - 拉伸canvas'
位图。另一方面,html properties
height
和width
会确定canvas'
位图的大小。
因此,您的案例中的解决方案是将代码更改为以下内容:
$("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.");
});
&#13;
canvas {
background-color: rgba(0, 0, 0, 0.3);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
资讯来源:Canvas is stretched when using CSS but normal with "width" / "height" properties