【发布时间】:2019-07-02 06:27:02
【问题描述】:
我想使用画布在一张图像上绘制多张图。
在我的代码中,我使用ctx.clearRect(0,0,canvas.width,canvas.height);
因此,它不允许我做多张图纸。如果我没有使用clearRect(),程序将无法正常运行。另外,我尝试更改clearRect() 的位置,但它也对我不起作用。
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0,0,canvas.width,canvas.height); //clear canvas
ctx.beginPath();
var width = mousex-last_mousex;
var height = mousey-last_mousey;
ctx.rect(last_mousex,last_mousey,width,height);
ctx.strokeStyle = "blue";
ctx.lineWidth = 10;
ctx.stroke();
//Canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//Variables
var canvasx = $(canvas).offset().left;
var canvasy = $(canvas).offset().top;
var last_mousex = last_mousey = 0;
var mousex = mousey = 0;
var mousedown = false;
//Mousedown
$(canvas).on('mousedown', function(e) {
last_mousex = parseInt(e.clientX - canvasx);
last_mousey = parseInt(e.clientY - canvasy);
mousedown = true;
});
//Mouseup
$(canvas).on('mouseup', function(e) {
mousedown = false;
});
//Mousemove
$(canvas).on('mousemove', function(e) {
mousex = parseInt(e.clientX - canvasx);
mousey = parseInt(e.clientY - canvasy);
if (mousedown) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
var width = mousex - last_mousex;
var height = mousey - last_mousey;
ctx.rect(last_mousex, last_mousey, width, height);
ctx.strokeStyle = "blue";
ctx.lineWidth = 10;
ctx.stroke();
}
//Output
$('#output').html('current: ' + mousex + ', ' + mousey + '<br/>last: ' + last_mousex + ', ' + last_mousey + '<br/>mousedown: ' + mousedown);
});
canvas {
cursor: crosshair;
border: 1px solid #000000;
background-image: url("kroki2v3.png");
background-repeat: no-repeat;
}
<html>
<head>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-2.1.3.js" integrity="sha256-goy7ystDD5xbXSf+kwL4eV6zOPJCEBD1FBiCElIm+U8=" crossorigin="anonymous"></script>
</head>
<body>
<canvas id="canvas" width="3200" height="1400"></canvas>
<div id="output"></div>
</body>
</html>
【问题讨论】:
标签: javascript jquery html canvas