我正在创建一个能够在画布上显示形状和颜色的网站,我的问题是图片不再显示了。
这是我的html示例:
// These are my choices for the first step in designing.
<input type="radio" id="shape_1" name="shape" onchange="display()" /> circle
<input type="radio" id="shape_2" name="shape" onchange="display()" /> rectangle
//2nd step, choose color
<input type="radio" id="color_1" name="color" onchange="display()" /> RED
//3rd step, choose image
<select name="picture" id="picture_display" onchange="display()" />
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<canvas id="displaycanvas" height="450px" width="820px" style="position:absolute;"> </canvas>
我的JS(单独):
function display() { //working fine
var canvas = document.getElementById('displaycanvas');
context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
function Choices() { //working fine too...
if (document.getElementById('color_1').checked) {
context.strokeStyle = "#FF0000";
}
if (document.getElementById('shape_1').checked) {
context.beginPath();
context.arc(95, 50, 40, 0, 2 * Math.PI);
context.stroke();
}
if (document.getElementById('shape_2').checked) {
context.beginPath();
context.rect(50, 27, 50, 100);
context.stroke();
}
}
function Picture() { //these part it won't work, I've tried to do something like this.
if (document.getElementById('picture_display').value == 'apple') {
document.getElementById('displaycanvas').src = 'http://www.logospike.com/wp-content/uploads/2015/12/Apple_Logo_Png_04.png';
}
if (document.getElementById('picture_display').value == 'orange') {
document.getElementById('displaycanvas').src = 'http://dailyrindblog.com/styleguide/web_version/logo_fruit.png';
}
}
}
我希望图像在前两个步骤的上方,但不会超出任何给定的形状(如果可能的话,如果不是很好)。我错过了什么或改变了一切? 提前非常感谢你!
对于拖动代码,您可以建议一些适用于此代码的链接。
答案 0 :(得分:1)
您必须获取对上下文的引用,然后加载图像对象,并在完成时在上下文中绘制图像
function Picture() {
var e = document.getElementById("picture_display");
var selValue1 = e.options[e.selectedIndex].value;
var context = document.getElementById('displaycanvas').getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
};
if (selValue1 === 'apple') {
imageObj.src = 'http://www.logospike.com/wp-content/uploads/2015/12/Apple_Logo_Png_04.png';
}
if (selValue1 === 'orange') {
imageObj.src = 'http://dailyrindblog.com/styleguide/web_version/logo_fruit.png';
}
}