使用canvas html使drawable字段可编辑

问题描述 投票:0回答:1

我想在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>

谢谢 !

javascript canvas
1个回答
0
投票

事实证明它有点复杂。

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

  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
}
© www.soinside.com 2019 - 2024. All rights reserved.