html2canvas边框半径不适用于img标签

时间:2014-06-15 10:06:33

标签: javascript jquery html5 canvas html5-canvas

需要帮助,当我通过css将边界半径应用于imgae时,它无法正确渲染,渲染图像应该是相同的预览图像。我使用html2canvas将div转换为图像。

附图供参考,第一个是带有border-radius的正常预览,第二个是没有border-radius的正常预览。

enter image description here

<div id="mydiv">
<img src="1.jpg" /> 
<p>text!</p>
</div>

<p>Generated image</p>
<div id="image">
<p>Image:</p>
</div>

CSS

    <style>
    #mydiv {
    width: 300px;
    height: 200px;
    background:#000;


}
#mydiv img {
    width: 200px;
    height: 200px;
    border-radius:100%;


}

    </style>

JS

html2canvas([document.getElementById('mydiv')], {
    onrendered: function (canvas) {
        //document.getElementById('canvas').appendChild(canvas);
        var data = canvas.toDataURL('image/png');
        // AJAX call to send `data` to a PHP file that creates an image from the dataURI string and saves it to a directory on the server

        var image = new Image();
        image.src = data;
        document.getElementById('image').appendChild(image);
    }
});

enter image description here

3 个答案:

答案 0 :(得分:0)

你可以通过css实现这个是如何

jsfiddle

.imageContainer{width: 400px; height: 300px; background-color:#000000;}

.imageDiv{width:200px;height:200px;background-size:cover;display:block;border-radius: 50%;-webkit-border-radius: 50%; -moz-border-radius: 50%;}

<div class="imageContainer">
  <div class="imageDiv" style="background-image:url('https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSD_lM5QOQ8JOhruhMB2pA_m5YvikpEoo_KOKB4zaajQIsaPBh1')">
  </div>
</div

答案 1 :(得分:0)

这是一个未解决的错误(已报告此问题):

http://github.com/niklasvh/html2canvas/issues/346

您可以使用canvas的裁剪功能作为解决方法。

演示:http://jsfiddle.net/m1erickson/8wL2q/

enter image description here

使用剪切区域而不是边框​​半径的示例代码:

// save the context in its unaltered state
ctx.save();

// fill canvas with black
ctx.fillStyle="black";
ctx.fillRect(0,0,canvas.width,canvas.height);

// create clipping region which will display portion of image
// The image will only be visible inside the circular clipping path
ctx.beginPath();
ctx.arc(100,100,100,0,Math.PI*2);
ctx.closePath();
ctx.clip();

// draw the image into the clipping region
ctx.drawImage(img,0,0);

// restore the context to its unaltered state
ctx.restore();

答案 2 :(得分:-1)

在css中使用border: solid windowtext 1.0pt;代替border:1px solid #fff;