我有以下代码:
<html>
<head>
</head>
<body>
<canvas id="canvasId" width="300" height="300"></canvas>
<script>
function square() {
var ctx = document.getElementById('canvasId').getContext('2d');
var col= document.getElementById("clr");
ctx.beginPath();
ctx.rect(10, 10, 70, 70);
ctx.fillStyle = 'yellow';
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = 'black';
ctx.stroke();
}
function triangle () {
var canvas = document.getElementById('canvasId');
var context = canvas.getContext('2d');
var col= document.getElementById("clr");
context.beginPath();
context.rect(85, 80, 200, 100);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 2;
context.strokeStyle = 'black';
context.stroke();
}
</script>
<p>Color <input type="color" id="clr" value="" /></p>
<input type="button" value="square" onclick="square()" />
<input type="button" value="triangle" onclick="triangle()" />
</body>
</html>
我对这个问题有疑问,我想当用户选择颜色并点击方形或三角形时,它会用他/她选择的颜色绘制它,我应该更改和添加什么?
答案 0 :(得分:2)
您需要使用实际绘制三角形的内容替换第二个rect(...)
调用,并且您可以通过访问其value
属性轻松地从输入字段中获取颜色。
Click here for my fork of your jsFiddle.
访问输入值的相关行在此处:
var col= document.getElementById("clr");
ctx.fillStyle = col.value;
现在进行三角形绘制(假设你想要一个等腰三角形来适应原始矩形):
context.beginPath();
context.moveTo(85, 180);
context.lineTo(185, 80);
context.lineTo(285, 180);
context.closePath();
答案 1 :(得分:1)
我在http://jsfiddle.net/rcondori/3gmosgq7/
中有一个例子这个例子是针对梯形的......
function isInsideBox(x, y, x1, x2, y1, y2) {
var a = getValueA(x1, x2, y1, y2);
var b = getValueB(x1, y1, a);
var auxY = (a * x) + b;
if (auxY <= y) {
return true;
} else {
return false;
}
}
function getValueA(x1, x2, y1, y2) {
return ((y1 - y2) / (x1 - x2));
}
function getValueB(x1, y1, a) {
return (y1 - (a * x1));
}