2014-04-26 108 views
0

试图编写一些代码,它会做以下事情。用线性渐变填充画布

用户将通过点击选择一种颜色,画布元素将填充该颜色作为渐变以及固定的白色color.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> 

回答

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/

+0

如果你提到我在我的代码中犯的错误,那将会很棒? –

+0

0的高度不显示任何内容:ctx.fillRect(0,0,200,0);它应该是ctx.fillRect(0,0,200,150); –

0

它看起来像你是惊人打我吧,我用jQuery-所以我可能会因为包括一个你没有要求的图书馆而得到分数。

但是,一个严重的问题,不要使用bgColor,它的弃用!

这是我had--

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; 
} 

http://jsfiddle.net/kmblackwood/z8UTa/2/

+0

还没有开始学习jquery:|。不管怎么说,还是要谢谢你 :) –