【发布时间】:2020-12-25 02:49:01
【问题描述】:
我正在尝试创建一个像绘画这样的应用程序,您可以在其中通过预览绘制基本形状。我为椭圆实现了一个绘制函数,接下来我想为一条线和一个矩形实现一个。但我不知道如何存储已经绘制的形状并在之后恢复它们。另外,如果我想使用预览进行绘制,我也不知道为什么需要两个画布元素。谢谢!
//JavaScript FILE
let canvas = document.getElementById("canvas");
let tempcanvas = document.getElementById("tempcanvas")
var ctx = tempcanvas.getContext('2d');
var mainctx = canvas.getContext('2d');
ctx.fillStyle="aqua";
ctx.fillRect(0, 0, canvas.width, canvas.height);
var widthCns = canvas.width, heightCns = canvas.height, x1, y1;
var isDown = false;
var savedDrawings = [];
//Desenare cu un singur tip de instrument (elipsă)
function drawEllipse(x1, y1, x2, y2){
var radiusX = (x2 - x1) * 0.5, /// radius for x based on input
radiusY = (y2 - y1) * 0.5, /// radius for y based on input
centerX = x1 + radiusX, /// calc center
centerY = y1 + radiusY,
step = 0.01, /// resolution of ellipse
a = step, /// counter
pi2 = Math.PI * 2 - step; /// end angle
/// start a new path
ctx.beginPath();
/// set start point at angle 0
ctx.moveTo(centerX + radiusX * Math.cos(0),
centerY + radiusY * Math.sin(0));
/// create the ellipse
for(; a < pi2; a += step) {
ctx.lineTo(centerX + radiusX * Math.cos(a),
centerY + radiusY * Math.sin(a));
}
/// close it and stroke it for demo
ctx.closePath();
ctx.strokeStyle = '#000';
ctx.stroke();
}
//Desenare cu un singur tip de instrument (dreptunghi)
function drawRect(){
}
//Desenare cu un singur tip de instrument (linie)
function drawLine(){
}
//Desenare cu mouse cu preview(elipsa, dreptunghi, line)
//Implementat: elipsa
/// handle mouse down
tempcanvas.onmousedown = function(e) {
// if(savedDrawings !== null)
// savedDrawings.pop();
// while( ctx!== null){
// ctx.restore();
// }
ctx.restore();
/// get corrected mouse position and store as first point
var rect = tempcanvas.getBoundingClientRect();
x1 = e.clientX - rect.left;
y1 = e.clientY - rect.top;
isDown = true;
}
/// clear isDown flag to stop drawing
tempcanvas.onmouseup = function() {
// savedDrawings.push({X: x1, Y: y1});
ctx.save();
isDown = false;
}
/// draw ellipse from start point
tempcanvas.onmousemove = function(e) {
if (!isDown) return;
var rect = tempcanvas.getBoundingClientRect(),
x2 = e.clientX - rect.left,
y2 = e.clientY - rect.top;
/// clear temporal canvas
ctx.clearRect(0, 0, widthCns, heightCns);
/// draw ellipse
drawEllipse(x1, y1, x2, y2);
}
//HTML FILE
<canvas id="canvas" width="800" height="500" padding="15px" position="absolute" background-color="aqua" style="border: 1px solid black">
</canvas>
<!-- canvas temporal -->
<canvas id="tempcanvas" width=800 height=500 padding="15px" position="absolute" background-color="aqua" style="border: 1px solid black"></canvas>
【问题讨论】:
标签: javascript html css