首页 > 解决方案 > 如何在clojurescript中嵌入js?

问题描述

假设我有一些纯 js 代码,例如:

    dimensions = {
        max_height : 800,
        max_width  : 600,
        width  : 800, // this will change
        height : 600, // this will change
        largest_property : function () {
            return this.height > this.width ? "height" : "width";
        },
        read_dimensions : function (img) {
            this.width = img.width;
            this.height = img.height;
            return this;
        },
        scaling_factor : function (original, computed) {
            return computed / original;
        },
        scale_to_fit : function () {
            var x_factor = this.scaling_factor(this.width,  this.max_width),
                y_factor = this.scaling_factor(this.height, this.max_height),

                largest_factor = Math.min(x_factor, y_factor);

            this.width  *= largest_factor;
            this.height *= largest_factor;
        }
    };

dimensions.read_dimensions(img).scale_to_fit();

canvas.width  = dimensions.width;
canvas.height = dimensions.height;
context.drawImage(img, 0, 0, dimensions.width, dimensions.height);

我想在 clojurescript 中使用这段代码,(.drawImage context img 0 0 (.-width dimensions) (.-height dimensions))而不必在 cljs 中重写整个东西。我怎样才能做到这一点?

标签: javascriptclojurescript

解决方案


您可以获取上面的代码并将其加载到页面<script>中加载已编译 CLJS 代码的标记之前。要加载它,您可以将其保存在不同的文件中,例如。dimensions.js并使用<script>标签加载它,或者您也可以将其嵌入到同一个 HTML 文档中<script>

dimensions对象将在global上下文中加载,因此您应该能够像js/dimensions在 ClojureScript 代码中一样访问它。


推荐阅读