0
我在javascript和帆布新的油漆三角工具,並想知道如何通過單擊並拖動鼠標繪製在畫布上的三角形就像我們在MS做塗料,其中的尺寸三角形取決於用戶拖動的次數。繪製MS使用HTML5畫布和JavaScript
我在javascript和帆布新的油漆三角工具,並想知道如何通過單擊並拖動鼠標繪製在畫布上的三角形就像我們在MS做塗料,其中的尺寸三角形取決於用戶拖動的次數。繪製MS使用HTML5畫布和JavaScript
這裏是一個起點:
//HTML elements
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//Current unconnected points
var mouse = [];
//Existing triangles
var triangles = [];
//The function that draws
function draw() {
//Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
//Draw existing triangles
for (var tIndex = 0; tIndex < triangles.length; tIndex++) {
var triangle = triangles[tIndex];
ctx.beginPath();
ctx.moveTo(triangle.a.x, triangle.a.y);
ctx.lineTo(triangle.b.x, triangle.b.y);
ctx.lineTo(triangle.c.x, triangle.c.y);
ctx.closePath();
ctx.stroke();
}
//Draw current mouse points
if (mouse.length > 0) {
ctx.beginPath();
ctx.moveTo(mouse[0].x, mouse[0].y);
}
if (mouse.length > 1) {
ctx.lineTo(mouse[1].x, mouse[1].y);
}
if (mouse.length > 0) {
ctx.stroke();
}
}
//Catch point
canvas.onclick = function eventHandler(event) {
//Add points to list
mouse.push({
x: event.layerX,
y: event.layerY
});
//If we have enough points, add a triangle
if (mouse.length >= 3) {
//Adding the triangle
triangles.push({
a: mouse[0],
b: mouse[1],
c: mouse[2]
});
//Clear points
mouse = [];
}
//Update canvas
draw();
};
body,
html,
* {
margin: 0px;
padding: 0px;
}
#canvas {
background-color: #ddd;
}
<canvas id="canvas" width="400" height="400"></canvas>
你將不得不自己創造的阻力效果。
如果你是新來的JavaScript,那麼你或許應該由學畫畫** **東西在畫布上開始。退房[MDN(https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes)的教程,並取回時,你有一些實際的代碼。 –