使用canvas html使可绘制字段可编辑



我想像javascript中的paint应用程序一样调整画布字段的大小,我该怎么办?

我的html文件是:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="paint.css">
<title>Paint</title>
</head>
<body>
<canvas id="canvas" style="border: solid 1px black">Your Browser does not support Canvas, please upgrade</canvas>
<script src="paint.js"></script>
</body>
</html>

谢谢!

它变得有点复杂。

调整画布大小可以清除它,因此您需要这样做:

  1. 创建新画布
  2. 指定尺寸
  3. 在新画布上画旧画布
  4. 用新画布替换旧画布

//Base canvas and dimensions
var canvas = document.body.appendChild(document.createElement("canvas"));
var width = canvas.height = canvas.width = 400;
var height = width;
var ctx = canvas.getContext("2d");
//Drawing variables
var lastPosition = null;
var drawing = false;
//Drawing functionality
function startDraw() {
drawing = true;
}
canvas.onmousedown = startDraw;
function stopDraw() {
drawing = false;
}
canvas.onmouseup = stopDraw;
canvas.onmouseleave = stopDraw;
function mouseMove(evt) {
var pos = {
x: evt.offsetX,
y: evt.offsetY
};
if (lastPosition !== null && drawing === true) {
ctx.beginPath();
ctx.moveTo(lastPosition.x, lastPosition.y);
ctx.lineTo(pos.x, pos.y);
ctx.closePath();
ctx.stroke();
}
lastPosition = pos;
}
canvas.onmousemove = mouseMove;
//Resizer functions
var resizerX = document.body.appendChild(document.createElement("button"));
resizerX.innerHTML = "Resize X";
resizerX.onclick = function() {
var newValue = null;
while (isNaN(newValue) || newValue < 10) {
newValue = parseInt(prompt("Insert new width", width.toString()));
}
var c = document.createElement("canvas");
width = newValue;
c.width = width;
c.height = height;
ctx = c.getContext("2d");
ctx.drawImage(canvas, 0, 0);
canvas.parentNode.replaceChild(c, canvas);
canvas = c;
canvas.onmousedown = startDraw;
canvas.onmouseup = stopDraw;
canvas.onmouseleave = stopDraw;
canvas.onmousemove = mouseMove;
};
var resizerY = document.body.appendChild(document.createElement("button"));
resizerY.innerHTML = "Resize Y";
resizerY.onclick = function() {
var newValue = null;
while (isNaN(newValue) || newValue < 10) {
newValue = parseInt(prompt("Insert new height", height.toString()));
}
var c = document.createElement("canvas");
height = newValue;
c.width = width;
c.height = height;
ctx = c.getContext("2d");
ctx.drawImage(canvas, 0, 0);
canvas.parentNode.replaceChild(c, canvas);
canvas = c;
canvas.onmousedown = startDraw;
canvas.onmouseup = stopDraw;
canvas.onmouseleave = stopDraw;
canvas.onmousemove = mouseMove;
};
canvas {
background-color: #eee
}

最新更新