开发者社区> 问答> 正文

将canvas的画append给body充当背景图,但出现奇怪效果

这是初始的样子,我想要的效果是这颗心不随滚动条滚动
screenshot
当我拖动滚动条的时候,这颗心跟着移动了,但原位置固定了另一颗心。screenshot继续拖动滚动条,screenshot由此可见,初始页面的心会随着滚动条移动,但同时有另一个心被固定在中间。
我只想要让这个心被固定在中心。不会因为滚动条的移动而出现另一颗心。
我通过JS建立canvas并将画设为背景图,JS代码如下:

var canvas = document.createElement('canvas');
var canvas_width = $("body").css("width").split("p")[0];
var canvas_height = $("body").css("height").split("p")[0];
document.body.appendChild(canvas);
canvas.id='homePageCanvas';
canvas.width = canvas_width; 
canvas.height = canvas_height;
//canvas.style.backgroundColor = '#F9D1D4';

drawHeartCurve(); //画出了一个心
document.body.style.background = "url('"+homePageCanvas.toDataURL()+"')";

document.body.style['background-attachment']='fixed';

HTML/CSS只有一个很高的div让滚动条出现。

展开
收起
小旋风柴进 2016-06-01 10:28:32 2966 0
2 条回答
写回答
取消 提交回答
  • 检查下drawHeartCurve时是不是没有用beginPath清除路径

    2019-07-17 19:22:50
    赞同 展开评论 打赏
  • 用圆点模拟了一下,实现效果如下

    <!DOCTYPE HTML>
    <html>
    <head>
    <title>背景固定居中</title>
    </head>
    <body>
    <table width="318" height="3081" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td>&nbsp;</td>
      </tr>
    </table>
    <canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;display:none;">
    Your browser does not support the canvas element.
    </canvas>
    <p>
    <script>
    var c=document.getElementById("myCanvas");
    var cxt=c.getContext("2d");
    cxt.fillStyle="#FF0000";
    cxt.beginPath();
    cxt.arc(70,18,15,0,Math.PI*2,true);
    cxt.closePath();
    cxt.fill();
    
    </script>
      <script language="javascript">
    document.body.style.backgroundImage="url('"+myCanvas.toDataURL()+"')";
    document.body.style.backgroundPosition="center";
    document.body.style.backgroundRepeat="no-repeat";
    document.body.style.backgroundAttachment="fixed";
      </script>
    </p>
    </body>
    </html>
    2019-07-17 19:22:50
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载