我在画布上画画板。我正在尝试使用jquery单击输入图像时更改画布的背景。
这是我的画布和按钮
的html代码画布:
<canvas id="myCanvas" width="640" height="480"></canvas>
点击输入类型图片:
<section id="canvascolor">
<input id="whitecanvas" class="canvasborder" type="image" src="images/whitecanvas.jpg" onClick="Whitecanvas()">
<input id="blackcanvas" class="canvasborder" type="image" src="images/blackcanvas.jpg" onClick="Blackcanvas()">
<input id="yellowcanvas" class="canvasborder" type="image" src="images/yellowcanvas.jpg" onClick="Yellowcanvas()">
<input id="bluecanvas" class="canvasborder" type="image" src="images/bluecanvas.jpg" onClick="Bluecanvas()">
<input id="redcanvas" class="canvasborder" type="image" src="images/redcanvas.jpg" onClick="Redcanvas()">
<input id="greencanvas" class="canvasborder" type="image" src="images/greencanvas.jpg" onClick="Greencanvas()">
</section>
CSS:
canvas{
background-image:url(../images/whitetexturepaper.jpg);
background-repeat:no-repeat;
background-size:cover;
}
我尝试过以下jquery,但它不起作用!:
function Whitecanvas(){
$("#myCanvas").css("background-image","url(images/whitetexturepaper.jpg)");
}
答案 0 :(得分:2)
在定义元素后将代码放在最后。
问题是你在元素在DOM之前定义函数。
更好地使用jQuery版本
从
部分的输入标签中删除onclick事件
$(document).ready(function () {
$("#canvascolor > input").click(function () {
var img = $(this).attr('src');
$('#myCanvas').css("background-image", "url(" + img + ")");
});
});
答案 1 :(得分:1)
尝试只使用一个ID
function Whitecanvas() {
$("#whitecanvas").css("background-image", "url(images/whitetexturepaper.jpg)");
}