【发布时间】:2016-06-19 16:45:43
【问题描述】:
使用画布我需要创建 4 个其他随机形状以随机大小和随机位置出现。到目前为止,我有随机圈子。但我也不知道如何获得其他形状。
在我的身体里
<canvas width='600' height='200' id='artCanvas'></canvas>
<form>
<input type='button' id='artButton' value='New Masterpiece'>
</form>
使用此代码,我需要以与随机创建圆圈相同的方式创建多个其他形状。
<script>
function makeTitle() {
//generate the title for your masterpiece
var lines =[['Meditative','Objective','Reflective'['Ellipses','Tranformation', 'State', 'Emotion', 'Composition']['I', 'II', 'III', 'IV','V']];
var title = '';
for (var i=0; i<lines.length; i++) {
var random = Math.floor(Math.random() * lines[i].length);
title += lines[i][random] + ' ';
};
return(title);
}
function artHandler() {
var title = makeTitle();
alert(title);
var canvas = document.getElementById('artCanvas');
var context = canvas.getContext('2d');
fillBackgroundColor(canvas, context);
var colors = ['white', 'yellow', 'blue', 'red'];
for (var i = 0; i < 20; i++) {
var color = colors[Math.floor(Math.random() * colors.length)];
drawCircle(canvas, context, color);
}
drawText(canvas, context, title);
}
function fillBackgroundColor(canvas, context) {
var colors = ['white', 'yellow', 'blue', 'red'];
var bgColor = colors[Math.floor(Math.random() * colors.length)];
context.fillStyle = bgColor;
context.fillRect(0, 0, canvas.width, canvas.height);
}
function degreesToRadians(degrees) {
return (degrees * Math.PI)/180;
}
// Draws a circle at a random location
function drawCircle(canvas, context, color) {
var radius = Math.floor(Math.random() * 40);
var x = Math.floor(Math.random() * canvas.width);
var y = Math.floor(Math.random() * canvas.height);
context.beginPath();
context.arc(x, y, radius, 0, degreesToRadians(360), true);
context.fillStyle = color;
context.fill();
}
function drawText(canvas, context, title) {
context.fillStyle = 'black';
context.font = 'bold 1em sans-serif';
context.textAlign = 'right';
context.fillText(title, canvas.width-20, canvas.height-40);
}
window.onload = function() {
var button = document.getElementById('artButton');
button.onclick = artHandler;
}
</script>
【问题讨论】:
-
我已将您的代码放在 JSFiddle 中,但它不起作用(甚至不为我画圈)。在
var lines的定义中缺少]似乎还有一个易于修复的错误。 -
它有效,在他的代码中你必须取消注释脚本中最后一个 win.onload 函数
-
请花几秒钟正确缩进您的代码。没有人愿意阅读一堵缩进的代码。让我们轻松为您提供帮助,您将获得更好的帮助。
标签: javascript canvas random