git clone https://github.com/LLK/scratch-render.git
cd scratch-render
npm install # 使用cnpm可能會安裝失敗
git下載慢的,可以考慮一下:加速下載
http://tool.mkblog.cn/github/
其實Scratch開發團隊已經實現了這個功能,只是我們要找到接口來調用。打開目錄下的/test/integration/index.html可以打開這個播放器Demo網頁。此時上傳sb文件會發現只能顯示代碼初始狀態的效果,這時需要添加一行代碼,添加vm.greenflag()給js執行,就可以實現播放的效果了。
這個網頁的代碼如下:
<body>
<script src="../../node_modules/scratch-vm/dist/web/scratch-vm.js"></script>
<script src="../../node_modules/scratch-storage/dist/web/scratch-storage.js"></script>
<script src="../../node_modules/scratch-svg-renderer/dist/web/scratch-svg-renderer.js"></script>
<!-- note: this uses the BUILT version of scratch-render! make sure to npm run build -->
<script src="../../dist/web/scratch-render.js"></script>
<canvas id="test" width="480" height="360" style="width: 480px"></canvas>
<input type="file" id="file" name="file">
<script>
// These variables are going to be available in the "window global" intentionally.
// Allows you easy access to debug with `vm.greenFlag()` etc.
window.devicePixelRatio = 1;
var canvas = document.getElementById('test');
var render = new ScratchRender(canvas);
var vm = new VirtualMachine();
var storage = new ScratchStorage();
var mockMouse = data => vm.runtime.postIOData('mouse', {
canvasWidth: canvas.width,
canvasHeight: canvas.height,
...data,
});
vm.attachStorage(storage);
vm.attachRenderer(render);
vm.attachV2SVGAdapter(new ScratchSVGRenderer.SVGRenderer());
vm.attachV2BitmapAdapter(new ScratchSVGRenderer.BitmapAdapter());
document.getElementById('file').addEventListener('click', e => {
document.body.removeChild(document.getElementById('loaded'));
});
document.getElementById('file').addEventListener('change', e => {
const reader = new FileReader();
const thisFileInput = e.target;
reader.onload = () => {
vm.start();
vm.loadProject(reader.result)
.then(() => {
// we add a `#loaded` div to our document, the integration suite
// waits for that element to show up to assume the vm is ready
// to play!
const div = document.createElement('div');
div.id='loaded';
document.body.appendChild(div);
// ------------------------------ //
vm.greenflag(); // 這裏添加這條語句
// ------------------------------ //
});
};
reader.readAsArrayBuffer(thisFileInput.files[0]);
});
</script>
</body>