下面的功能我用来在画布上随机画线。我使用了fabricjs来绘制其他元素。
问题::
问题是当我在画布上点击画布后,绘制的所有元素都变得不可见。
function drawOnCanvas() {
// We want to store the state of the canvas, before we apply the change on it. That way we can
// revert back to the state before the canvas was changed.
saveRestorePoint();
console.log('inside draw on canvas');
var canvasContext = document.getElementById("design_text").getContext("2d");
// Choose random coordinates for start and end point of the line we will drive
var xFrom = getRandomInt(0, canvasContext.canvas.width);
var yFrom = getRandomInt(0, canvasContext.canvas.height);
var xTo = getRandomInt(0, canvasContext.canvas.width);
var yTo = getRandomInt(0, canvasContext.canvas.height);
// .save() and .restore() only save and restore the fill style of the canvas context.
// They are not relevant to the canvas drawing state.
canvasContext.save();
// We choose a random color for our line
canvasContext.strokeStyle = randomColor();
// and a random width
canvasContext.lineWidth = getRandomInt(1, 4);
// It is important to .beginPath() and .closePath(), otherwise you will end up with artifacts
canvasContext.beginPath();
// We go to the starting position of the line
canvasContext.moveTo(xFrom, yFrom);
// and draw the line to its end position
canvasContext.lineTo(xTo, yTo);
// then we color it
canvasContext.stroke();
// and close the shape
canvasContext.closePath();
// We restore the original fill state (color, width, etc...) of the canvas
canvasContext.restore();
}
/*** Those are some helper functions, not directly related to the Canvas ***/
// Get a random number in a range (from, to)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Returns a random hex number
function randomColor() {
var rint = Math.round(0xffffff * Math.random());
return ('#0' + rint.toString(16)).replace(/^#0([0-9a-f]{6})$/i, '#$1');
}