尝试编写一些代码来执行以下操作。
用户将通过单击选择一种颜色,并且画布元素将填充用作渐变的颜色以及固定的白色.code似乎不起作用。
<html>
<head>
<style>
#chart{width:80px;height:80px;position:fixed;top:20px;left:20px;}
#mycanvas{width:200px;height:150px;position:fixed;top:250px;left:200px;border:1px solid black;}
</style>
</head>
<body>
<script>
function mygradient(colors){
var canvas=document.getElementById('mycanvas');
var ctx=canvas.getContext("2d");
var grad=ctx.createLinearGradient(0,0,190,0);
grad.addColorStop(0,colors);
grad.addColorStop(1,"white");
ctx.fillStyle=grad;
ctx.fillRect(0,0,200,0);
}
</script>
<table id="chart">
<tr>
<td bgColor="#FF8000" onClick="mygradient(this.bgColor);"></td>
<td bgColor="#FFBF00" onClick="mygradient(this.bgColor);"></td>
</tr>
</table>
<canvas id="mycanvas"style=""></canvas>
</body>
</html>
答案 0 :(得分:1)
我对它进行了一些研究,现在它起作用了:
<html>
<head>
<style>
#chart{width:80px;height:80px;position:fixed;top:20px;left:20px;}
#mycanvas{width:200px;height:150px;position:fixed;top:250px;left:200px;border:1p x solid black;}
</style>
</head>
<body>
<script>
function mygradient(colors){
var canvas=document.getElementById('mycanvas');
var ctx=canvas.getContext("2d");
var grd=ctx.createLinearGradient(0,0,170,0);
grd.addColorStop(0,colors);
grd.addColorStop(1,"white");
ctx.fillStyle=grd;
ctx.fillRect(20,20,150,100);
}
</script>
<table id="chart">
<tr>
<td bgColor="#FF8000" onClick="mygradient(this.bgColor);"></td>
<td bgColor="#FFBF00" onClick="mygradient(this.bgColor);"></td>
</tr>
</table>
<canvas id="mycanvas"style=""></canvas>
</body>
的jsfiddle:http://jsfiddle.net/4MBtp/
答案 1 :(得分:0)
看起来像你很神奇打败了我,我使用了jQuery - 所以我可能会因为包含你没有要求的图书馆而获得积分。
但严肃地说,不要使用bgColor,不推荐使用它!
这就是我所拥有的 -
JS:
var $swatch = $(".swatch");
$swatch.click(function (e) {
color = $(this).css("background-color");
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.rect(0, 0, canvas.width, canvas.height);
var grd = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
grd.addColorStop(0, color);
grd.addColorStop(1, '#fff');
ctx.fillStyle = grd;
ctx.fill();
});
HTML:
<table id="chart">
<tr>
<td class="swatch orange"></td>
<td class="swatch yellow"></td>
</tr>
</table>
<canvas id="myCanvas"></canvas>
CSS:
#chart {
width:80px;
height:80px;
position:fixed;
top:20px;
left:20px;
}
.yellow {
background-color: #FFBF00;
}
.orange {
background-color: #FF8000;
}
#myCanvas {
width:200px;
height:150px;
position:fixed;
top:250px;
left:200px;
border:1px solid black;
}