在画布中隐藏/显示图像

时间:2017-02-06 19:38:58

标签: javascript html canvas upload html5-canvas

我正在创建一个页面,我希望人们能够重叠图像,然后将它们上传到我的服务器。

我已经构建了上传页面,并且我已经在画布中放置了两个测试图像。唯一的问题是能够通过按钮或复选框隐藏/显示这两个图像。

我已在此处上传了测试页:http://kaosmos.no/bokbodentest2/upload.html

这是我的画布代码:

<input type="checkbox"/>Check to hide img1
<input type="checkbox"/>Check to hide img2


<img class="bilder" id="img1" src="test1.png">
<img class="bilder" id="img2" src="test2.png">
<canvas id="canvas"></canvas>

<script type="text/javascript">
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

canvas.width = img1.width;
canvas.height = img1.height;

context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);


</script>

和CSS:

canvas {
border: solid;
overflow: hidden;
}

canvas img {
width: 600px;
position: absolute;
mix-blend-mode: multiply;
}

.bilder {
display: none;
}

显示:无;在&#34; bilder&#34; class是为了使图像在画布外不可见。如何制作隐藏/显示这些图像的功能?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

因为当一个图像被绘制到画布上时,它不再链接到DOM中的原始元素,你想要将它隐藏在画布上,所以每次输入时你都需要重绘画布更改,而不是调用相关的context.drawImage函数。这些方面的东西:

<input type="checkbox" onchange="draw()"/>Check to hide img1
<input type="checkbox" onchange="draw()"/>Check to hide img2


<img class="bilder" id="img1" src="test1.png">
<img class="bilder" id="img2" src="test2.png">
<canvas id="canvas"></canvas>

<script type="text/javascript">
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var inputs = document.querySelectorAll('input[type="checkbox"]');

canvas.width = img1.width;
canvas.height = img1.height;
function draw(){
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.globalAlpha = 1.0;
    if(inputs[0].checked){
        context.drawImage(img1, 0, 0);
    }
    context.globalAlpha = 0.5; //Remove if pngs have alpha
    if(inputs[1].checked){
        context.drawImage(img2, 0, 0);
    }
}

</script>