html5的canvas显示html,如何让HTML5画布显示HTML?

1

You could potentially create a basic recursive function to descend into the children of the element that uses a switch or an event handler object to handle certain elements. I demonstrate the former here:

您可以创建一个基本的递归函数,以下降到使用switch或事件处理程序对象来处理某些元素的

元素的子元素。我在这里展示前者:

var canvas = document.getElementById('canvas');

var ctx = canvas.getContext('2d');

ctx.clearRect( 0, 0, canvas.width, canvas.height );

var y = 50; //Set to largest text

var offset = 25;

(function descend(parent){

for( var i = 0; i < parent.childNodes.length; i++ ){

var child = parent.childNodes[i];

var name = child.tagName;

var val = child.innerHTML;

if( child.hasChildNodes() ) descend(child);

switch( name ){

case 'H1':

ctx.font = "normal 48px Arial";

y += 25;

ctx.fillText( val, offset, y );

y += 25;

break;

case 'H2':

ctx.font = "normal 36px Arial";

y += 20;

ctx.fillText( val, offset, y );

y += 20;

break;

case 'H3':

ctx.font = "normal 24px Arial";

y += 12;

ctx.fillText( val, offset, y );

y += 12;

break;

default:

break;

}

}

})( canvas );

H1

H2

H3

This code utilizes a function to descend into the element tree of the element and handles certain elements with different rendering techniques. It may seem a little bit excessive, but if you are looking for an effective way to achieve that goal, this method works. Especially with the flexibility of rendering, that being your ability to choose how to render which elements how you want to, so if you want to render all 's red for some reason, you can do that. The function I provided is extremely basic, only rendering

-

, and when you start to mix them around inside the , it gets a little "render jerky". But it demonstrates the concept well, and I think you may find it effective.

此代码利用函数下降到元素的元素树中,并使用不同的呈现技术处理某些元素。它可能看起来有点过分,但如果您正在寻找实现该目标的有效方法,则此方法可行。特别是在渲染的灵活性方面,你可以选择如何渲染你想要的元素,所以如果你想出于某种原因渲染所有的红色,你就可以做到。我提供的功能是非常基本的,只渲染

-

,当你开始在里面混合它们时,它会得到一点“渲染生涩”。但它很好地证明了这个概念,我认为你可能会发现它有效。

Although the thoughts posted in the comments are definitely admirable, if you are looking for flexibility or would rather have control over rendering, this may be the solution you are looking for.

虽然评论中发布的想法绝对令人钦佩,但如果您正在寻求灵活性或者宁愿控制渲染,那么这可能是您正在寻找的解决方案。

Note: I will say that the code does not detect updates in the element's DOM; you will need a mutation observer for that. You might also wish to place the code inside of a function that is run when the page is loaded, so that the JavaScript runtime can actually find your element.

注意:我会说代码不会检测

元素的DOM中的更新;你需要一个变异观察者。您可能还希望将代码放在加载页面时运行的函数内,以便JavaScript运行库可以实际找到您的

元素。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值